package com.queming.core.entity;

import com.queming.core.enums.Gender;

import lombok.Data;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author chencidiao
 * @date 2022/04/17 16:53
 **/
//@Entity是jpa中标识持久层的

@Entity
@Data

public class User extends AbstractEntity implements UserDetails {
    @Column(unique = true)
    private String username;
    private String nickname;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "roles_id", referencedColumnName = "id"))
    private List<Role> roles;

    private String password;
    @Enumerated(EnumType.STRING)
    private Gender gender;
    //枚举类型,通过注解指定传入的是枚举的字符，而不是代表的数字

    private Boolean locked = false;
    private Boolean enable = true;
    private String lastLoginIp;
    private Date lastLoginTime;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for(Role role:roles){
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !getLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return getEnable();
    }
}
